package com.example.fruitdemo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fruitdemo.mapper.OrderMapper;
import com.example.fruitdemo.pojo.*;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.*;
import com.example.fruitdemo.util.Code;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
   @Autowired
   private GoodService goodService;
   @Autowired
   private StringRedisTemplate redisTemplate;
   @Autowired
   private UserService userService;
   @Autowired
   private GoodPayService goodPayService;
   @Autowired
   private AddressService addressService;
    @Override
    public R<String> buynow(Long goodid, Integer number, String signalprice,String authorization) {

        //先查商品信息
        Good good = goodService.getById(goodid);
        //给good转型
        GoodBuy goodBuy = new GoodBuy();
        goodBuy.setGoodname(good.getGoodname());
        goodBuy.setNumber(number);
        goodBuy.setSignalprice(good.getSignalprice());
        goodBuy.setGoodid(good.getId());
        goodBuy.setPic(good.getPic());

        Double totalprice=Double.parseDouble(signalprice)*number;
        //保留两位小数
        double total = Double.parseDouble(new DecimalFormat("#.00").format(totalprice));

        goodBuy.setTotalprice(total);
        goodBuy.setCreatetime(LocalDateTime.now());
        goodBuy.setUpdatetime(LocalDateTime.now());
        //都存入购物车
        List<GoodBuy> goodBuys=new ArrayList<>();
        goodBuys.add(goodBuy);
        Cart cart=new Cart(goodBuys,1,total);
        //先把用户id查出来，以用户id为key
        Long userid = userService.getidByAuth(authorization);
        //把立即买存入redis中
        redisTemplate.opsForValue().set(Code.USER_BUY_NOW+userid.toString(), JSON.toJSONString(cart));
        return R.Ok();
    }

    /**
     * 返回立即买的商品还有购物车里的商品
     * @param authorization
     * @return
     */
    @Override
    public R<Cart> getgoods(String authorization) {
//       int flag=1,ifnull=0;
//        //先把用户id查出来，以用户id为key
//        Long userid = userService.getidByAuth(authorization);
//
//        if(redisTemplate.opsForValue().get(Code.USER_BUY_NOW+ userid.toString())==null||redisTemplate.opsForValue().get(Code.USER_BUY_NOW+ userid.toString()).isEmpty())
//        {
//            //如果立即购买为空，则直接返回购物车里的商品
//            String cartjson = redisTemplate.opsForValue().get(Code.USER_CART + userid);
//            //转换为VCart对象
//            Cart cart1 = JSONObject.parseObject(cartjson, Cart.class);
//            return R.Ok(cart1);
//        }
//       else {
//            String json = redisTemplate.opsForValue().get(Code.USER_BUY_NOW + userid.toString());
//
//            //转为Cart对象
//            Cart cart = JSONObject.parseObject(json, Cart.class);
//            //获取商品信息
//            List<GoodBuy> goodList = cart.getGoodList();
//            GoodBuy goodBuy = goodList.get(0);  //其实就一个
//            //System.err.println(goodBuy);
//            //再去获取购物车里的内容
//
//            if (redisTemplate.opsForValue().get(Code.USER_CART + userid) == null || redisTemplate.opsForValue().get(Code.USER_CART + userid).isEmpty()) {
//                //购物车是空的，直接返回立即购买的商品
//                return R.Ok(cart);
//            } else {
//                String cartjson = redisTemplate.opsForValue().get(Code.USER_CART + userid);
//                //转换为VCart对象
//                Cart cart1 = JSONObject.parseObject(cartjson, Cart.class);
//                //获取商品信息
//                List<GoodBuy> cartgoods = cart1.getGoodList();
//                //遍历信息
//                for (GoodBuy good : cartgoods) {
//                    //如果要购买的的商品和购物车里的重复，
//                    //则应该跟新更新购物车
//                    if (goodBuy.getGoodid() == good.getGoodid()) {
//                        flag = 0;
//                        //吧总价先计算一下(数量不变)
//                        cart1.setTotalprice(cart1.getTotalprice() - good.getTotalprice() + goodBuy.getTotalprice());
//                        BeanUtils.copyProperties(goodBuy, good);
//                    }
//                }
//                if (flag == 0 ) {
//                    //直接返回购物车里的商品就行
//                    cart1.setGoodList(cartgoods);
//                    return R.Ok(cart1);
//                }
//                if (flag == 1 ) {
//                    //没有重复的，则要把立即买的和购物车里的一起返回
//                    cartgoods.add(goodBuy);
//                    //计算钱和数量
//                    Cart newcart = new Cart(cartgoods, cart1.getNumber() + 1, cart1.getTotalprice() + cart.getTotalprice());
//                    return R.Ok(newcart);
//                } else return R.Err("错误");
//            }
//        }
        Long userid = userService.getidByAuth(authorization);

         if(redisTemplate.opsForValue().get(Code.USER_CART + userid)==null||redisTemplate.opsForValue().get(Code.USER_CART + userid).isEmpty())
         {
             return R.Err("购物车为空");
         }else {
             String json = redisTemplate.opsForValue().get(Code.USER_CART + userid);
             Cart cart = JSONObject.parseObject(json, Cart.class);
             return R.Ok(cart);
         }

    }

    @Override
    public R<Cart> getGoodBuyNow(String authorization) {
        Long userid = userService.getidByAuth(authorization);
        String json = redisTemplate.opsForValue().get(Code.USER_BUY_NOW + userid);
        Cart cart = JSONObject.parseObject(json, Cart.class);
        return R.Ok(cart);
    }

    //添加到购物车
    @Override
    public R<String> tocart(Long goodid, Integer number, String signalprice, String authorization) {
        int flag=1;
        //先查商品信息
        Good good = goodService.getById(goodid);
        //给good转型
        GoodBuy goodBuy = new GoodBuy();
        goodBuy.setGoodname(good.getGoodname());
        goodBuy.setNumber(number);
        goodBuy.setSignalprice(good.getSignalprice());
        goodBuy.setGoodid(good.getId());
        goodBuy.setPic(good.getPic());

        Double totalprice = Double.parseDouble(signalprice) * number;
        //保留两位小数
        double total = Double.parseDouble(new DecimalFormat("#.00").format(totalprice));

        goodBuy.setTotalprice(total);
        goodBuy.setCreatetime(LocalDateTime.now());
        goodBuy.setUpdatetime(LocalDateTime.now());
        //在存入之前先吧数据查出来在基础上添加
        //先把用户id查出来，以用户id为key
        Long userid = userService.getidByAuth(authorization);
        //String json = redisTemplate.opsForValue().get("usercat:" + userid.toString());

        if(redisTemplate.opsForValue().get(Code.USER_CART + userid.toString())==null||redisTemplate.opsForValue().get(Code.USER_CART + userid).isEmpty()){
            //json为空（购物车为空）
            List<GoodBuy> goodBuys=new ArrayList<>();
            goodBuys.add(goodBuy);
            Cart newCart = new Cart(goodBuys, 1, totalprice);
            //以用户id为key,把购物车存入redis中
            redisTemplate.opsForValue().set(Code.USER_CART + userid, JSON.toJSONString(newCart));
            return R.Ok(Code.FLAG_TRUE_CODE);
        }

        else {
            String json = redisTemplate.opsForValue().get(Code.USER_CART + userid);
            //转为Cart对象
            Cart cart = JSONObject.parseObject(json, Cart.class);
            //获取商品信息
            List<GoodBuy> goodList = cart.getGoodList();
            //设置一个flag
            //int flag = 1;
            //遍历商品，如果有重复的商品，更新记录
            for (GoodBuy oldgood : goodList) {
                if (oldgood.getGoodid() == goodBuy.getGoodid()) {
                    flag = 0;
                    //重复，跟新记录
                    cart.setTotalprice(cart.getTotalprice()-oldgood.getTotalprice()+goodBuy.getTotalprice());
                    BeanUtils.copyProperties(goodBuy,oldgood);
                }
            }
            if (flag == 0) {
                cart.setGoodList(goodList);
                //存入新购物车

                //以用户id为key,把购物车存入redis中
                redisTemplate.opsForValue().set(Code.USER_CART + userid, JSON.toJSONString(cart));
                //重复
                return R.Ok(Code.FLAG_FLASE_CODE);
            } else {
                //不重复，在此基础上添加商品信息,数量，总价
                goodList.add(goodBuy);
//                number = cart.getNumber() + 1;
                total = cart.getTotalprice() + total;
                //都存入购物车
                Cart newcart = new Cart(goodList, cart.getNumber()+1, total);
                //以用户id为key,把购物车存入redis中
                redisTemplate.opsForValue().set(Code.USER_CART + userid, JSON.toJSONString(newcart));
                return R.Ok(Code.FLAG_TRUE_CODE);
            }
        }



    }

    @Override
    public R<String> removeGood(String authorization, String goodid) {
        //先查询id
        Long userid = userService.getidByAuth(authorization);

        long longgoodid = Long.parseLong(goodid);

        //以id为key
        String s = redisTemplate.opsForValue().get(Code.USER_CART + userid);
        Cart cart = JSONObject.parseObject(s, Cart.class);
        List<GoodBuy> goodList = cart.getGoodList();

        int index = 0;

         for (int i=0;i<goodList.size();i++){
            if(goodList.get(i).getGoodid()==longgoodid) {
                 //先把数量和总价减少
                index=i;
                cart.setNumber(cart.getNumber()-1);
                cart.setTotalprice(cart.getTotalprice()-goodList.get(i).getTotalprice());
                }
            }

        goodList.remove(index);

        if (goodList.size()==0){
            //删除完了，要吧购物车删了
            redisTemplate.delete(Code.USER_CART+userid);
            return R.Ok("删除完了!");
        }else {
            cart.setGoodList(goodList);
            //重新存入
            redisTemplate.opsForValue().set(Code.USER_CART+userid,JSON.toJSONString(cart));
            return R.Ok();
        }
    }

    @Override
    public R<String> suborder(OrderDto orderDto) {
        //先把立即购买和购物车清空
        redisTemplate.delete(Code.USER_CART+orderDto.getUserid());
        redisTemplate.delete(Code.USER_BUY_NOW+orderDto.getUserid());
        //查询收货人的id
        Long receiveid = addressService.getidByName(orderDto.getReceiver());


        List<GoodPay> goodPays = orderDto.getGoodlist();

        Order order = new Order();
        BeanUtils.copyProperties(orderDto,order,"goodlist");
        System.err.println(order.getPayway());

        //设置支付方式
        if(order.getPayway().equals("1")){
            order.setPayway("货到付款");
        }else if(order.getPayway().equals("2")){
            order.setPayway("微信支付");
        }else if(order.getPayway().equals("3")){
            order.setPayway("支付宝支付");
        }else order.setPayway("银行卡支付");
         order.setStatus(0);
         order.setReceiverid(receiveid);

        boolean flag = this.save(order);
        if(flag){
            //保存成功，拿到id
            Long id = order.getId();

            //给goodPay赋值
            for (GoodPay goodPay : goodPays) {

                goodPay.setOrderid(id);
                goodPay.setUserid(orderDto.getUserid());
                goodPay.setReceiverid(receiveid);
                //存入数据库
                goodPayService.save(goodPay);
            }
        }else return R.Err("服务器错误！提交失败");

        return R.Ok();
    }

    /**
     * 分页查询
     * @param authorization
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R<Page> getPage(String authorization, int page, int pageSize) {
        Long userid = userService.getidByAuth(authorization);

        LambdaQueryWrapper<Order> orderWrapper=new LambdaQueryWrapper<>();
        //分页构造器
        Page<Order> pageinfo=new Page<>(page,pageSize);
        orderWrapper.eq(Order::getUserid,userid).orderByDesc(Order::getCreatetime);
        this.page(pageinfo,orderWrapper);
        //把记录拿出来,遍历
        List<Order> orderList = pageinfo.getRecords();


    List<OrderDto> orderDtoList = orderList.stream().map((item)->{
            OrderDto orderDto=new OrderDto();
            BeanUtils.copyProperties(item,orderDto);

        Long receiverid = orderDto.getReceiverid();
        Long orderid = orderDto.getId();
        LambdaQueryWrapper<GoodPay> goodPayWrapper=new LambdaQueryWrapper<>();
         //收货人id和订单id都得一致
        goodPayWrapper.eq(GoodPay::getReceiverid,receiverid).eq(GoodPay::getOrderid,orderid);

        List<GoodPay> goodPays = goodPayService.list(goodPayWrapper);
        //给每个订单对象设置商品信息
            orderDto.setGoodlist(goodPays);
            return orderDto;
        }).collect(Collectors.toList());
       //在给分页对象设置记录
        Page<OrderDto> orderDtoPage = new Page(page, pageSize);
         orderDtoPage.setRecords(orderDtoList);
         orderDtoPage.setTotal(pageinfo.getTotal());
         orderDtoPage.setCurrent(pageinfo.getCurrent());
        return R.Ok(orderDtoPage);
    }

    @Override
    public R<Page> pageBymsg(String authorization, int page, int pageSize,String searchmsg) {
        System.out.println(page+"  "+pageSize+ "  " +searchmsg);
        Long _userid = userService.getidByAuth(authorization);
        LambdaQueryWrapper<Order> orderWrapper =new LambdaQueryWrapper<>();
        try{
            long searchid = Long.parseLong(searchmsg);
            orderWrapper.like(searchmsg!=null,Order::getId,searchid);

        }catch (Exception e){
            orderWrapper.like(searchmsg!=null,Order::getReceiver,searchmsg);

        }finally {

            orderWrapper.eq(Order::getUserid,_userid);
            Page<Order> orderPage=new Page<>(page,pageSize);
            this.page(orderPage,orderWrapper);
            List<Order> orderList = orderPage.getRecords();

            List<OrderDto> orderDtoList = orderList.stream().map((item)->{
                OrderDto orderDto=new OrderDto();
                BeanUtils.copyProperties(item,orderDto);

                Long receiverid = orderDto.getReceiverid();
                Long orderid = orderDto.getId();
                LambdaQueryWrapper<GoodPay> goodPayWrapper=new LambdaQueryWrapper<>();
                //收货人id和订单id都得一致
                goodPayWrapper.eq(GoodPay::getReceiverid,receiverid).eq(GoodPay::getOrderid,orderid);

                List<GoodPay> goodPays = goodPayService.list(goodPayWrapper);
                //给每个订单对象设置商品信息
                orderDto.setGoodlist(goodPays);
                return orderDto;
            }).collect(Collectors.toList());
            //在给分页对象设置记录
            Page<OrderDto> orderDtoPage = new Page(page, pageSize);
            orderDtoPage.setRecords(orderDtoList);
            orderDtoPage.setTotal(orderPage.getTotal());
            orderDtoPage.setCurrent(orderPage.getCurrent());
            return R.Ok(orderDtoPage);
        }
    }


}
